//变量及常量定义
var PLUGIN_SOURCE_LANGUAGE = "";//插件源语言
var PLUGIN_TARGET_LANGUAGE = "";//插件目标语言
var PLUGIN_SELECT_TRANSLATION = "";//划词翻译功能开关标识
var LANGUAGE_TYPE_LIST = {};//语种列表
var LANGUAGE_TYPE_LIST_DEFINED = {"zh":"中文","en":"英文","ru":"俄语","pt":"葡语","fr":"法语"};//语种列表拉取失败情况下的默认语种列表


//临时变量定义
var total_number_of_content = 0;//网页翻译,翻译字符长度计算
var request_iter = 0;
var sourceMap = {};//查看原文时缓存
var targetMap = {};//查看译文时缓存

var sourceNewObj = {};//查看原文时缓存
var targetNewObj = {};//查看译文时缓存

var dict = {};
// var transURL = "http://192.168.102.23:8080/front/plugin/translate";//翻译接口
//content script维度监听器
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
	
	//插件显示/移除动作监听
	if (request.action == "action_change_plugin_bar") {

		//恢复最后一次网页缓存信息
		sourceMap = request.sourceMap;
		targetMap = request.targetMap;
		dict = request.dict;

		if(request.PLUGIN_ON_OFF == "on"){
			//显示插件
			change_plugin_bar(1,request);
		}else if(request.PLUGIN_ON_OFF == "off"){
			//移除插件
			change_plugin_bar(0,request);
		}
		
		//配置翻译功能条默认源语言和目标语言
		config_source_target_language_bar(request);

	}
});

//配置翻译功能条默认源语言和目标语言
function config_source_target_language_bar(request){
	PLUGIN_SOURCE_LANGUAGE = request.SOURCE_LANGUAGE;//当前页面主要语言
	PLUGIN_TARGET_LANGUAGE = request.TARGET_LANGUAGE;//用户配置默认语言,插件初始化时默认为英文

	//页面语种识别,依托于谷歌浏览器的引擎识别页面语种
	if(PLUGIN_SOURCE_LANGUAGE == "und"){//如果是未识别的语言,策略：将源语言和目标语言置为相同
		PLUGIN_SOURCE_LANGUAGE == PLUGIN_TARGET_LANGUAGE;
	}


}

//改变翻译功能条显示/移除
function change_plugin_bar(flag,request){
	if(flag == 0){
		remove_plugin_box();//移除页面划词翻译功能
		remove_plugin_bar();//移除翻译插件功能条
		//转换为显示原文
		Suffer_Source(1);
		
		//发送移除消息到background,目的为改变localStorage状态
		chrome.runtime.sendMessage({plugin_status:0},function(response){});

	}else if(flag == 1){

		language_type_list_init(request);//语种列表初始化

		show_plugin_bar(request.IS_AUTO);//开启翻译功能条
		show_plugin_box();//开启划词翻译功能

	}
	
}

//语种列表初始化
function language_type_list_init(request){

	LANGUAGE_TYPE_LIST = request.LANGUAGE_TYPE_LIST;//复制给全局变量以供划词翻译使用

}

//翻译功能条显示
function show_plugin_bar(isAuto){

	document.body.style.marginTop = "50px";
	document.body.style.position = "relative";

	$("#yeetool").remove();
	yeetool = document.createElement('iframe');	
	document.body.appendChild(yeetool);



	yeetool.id = 'yeetool';
	yeetool.style.position = "fixed";
	yeetool.style.width = '100%';
	yeetool.style.top = 0;
	yeetool.style.left = 0;
	yeetool.style.zIndex = 2147483646;
	yeetool.style.height = '40px';
	yeetool.style.border = '0px';
	yeetool.scrolling='no';
	yeetool.src=chrome.extension.getURL("content.html");
	$("#yeetool").css("box-shadow","0 0 5px #888");

	//插件页面动作请求监听
	bar_event_listener();

	//发送插件功能条创建初始化信息到功能条页面脚本
	send_msg_init(isAuto);

}


//翻译功能条移除
function remove_plugin_bar(){
	document.body.style.marginTop = 0;
	document.body.style.position = '';
	yeetool = $('#yeetool');
	if(yeetool != null){
		$("#yeetool").remove();
	}
}

//划词翻译功能开启
function show_plugin_box(){
	yeetool = document.getElementById('yeetool');
	PLUGIN_SELECT_TRANSLATION = "stop";
	yeetool.contentWindow.postMessage({
		select_translation_flag : PLUGIN_SELECT_TRANSLATION
	}, "*");
	//渲染划词翻译匡
	document.onmouseup = addYeebox;
}


//划词翻译功能关闭
function remove_plugin_box(){
	yeetool = document.getElementById('yeetool');
	PLUGIN_SELECT_TRANSLATION = "start";
	//移除划词翻译匡
	removeYeebox();
	document.onmouseup="";
	yeetool.contentWindow.postMessage({
		select_translation_flag : PLUGIN_SELECT_TRANSLATION
	}, "*");

}
var newobj;
//通道通信事件监听,监听来自插件页面脚本的action动作请求
function bar_event_listener(){
	var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
	var eventer = window[eventMethod];
	var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
	eventer(messageEvent,postMessageListener , false);
}
function postMessageListener(e) {
	if(e.data.action=="YEEKIT_SUFFER_SOURCE"){
		// 查看原文
		Suffer_Source(0);
	}else if(e.data.action=="YEEKIT_SUFFER_TARGET"){
		// 查看译文
		Suffer_Target();
	}else if(e.data.action=="YEEKIT_REMOVE_PLUGIN"){
		//移除插件
		change_plugin_bar(0);
		window.removeEventListener(((window.addEventListener ? "addEventListener" : "attachEvent")== "attachEvent" ? "onmessage" : "message"),postMessageListener);


	}else if(e.data.action=="YEEKIT_TRANSLATE"){
		
		//翻译开始前存储网页对象作为原文
		//翻译结束后存储网页对象作为译文
		
		//存储原文
		save_source_element();
		//翻译开始
		total_number_of_content = get_total_number_of_translation();//统计翻译字符总量

		transBtnClick(e.data.sourceLang, e.data.targetLang);//开始翻译	

		
		//发请求到background,记录点击翻译次数日志
		chrome.runtime.sendMessage({log_plugin_translate:true},function(response){});
	
	}else if(e.data.action=="YEEKIT_NEVER_REMIND"){
		PostDate();
		// console.info("stop for one week");
	}else if(e.data.action=="YEEKIT_SELECT_TRANSLATION_ON"){
		//开启划词翻译
		show_plugin_box();

		//发请求到background,记录点击开启划词翻译记录日志
		chrome.runtime.sendMessage({log_plugin_words_open:true},function(response){});

	}else if(e.data.action=="YEEKIT_SELECT_TRANSLATION_OFF"){
		//关闭划词翻译
		remove_plugin_box();

		//发请求到background,记录点击关闭划词翻译记录日志
		chrome.runtime.sendMessage({log_plugin_words_close:true},function(response){});

	}else if(e.data.action == "RELOAD_PLUGIN"){
		change_plugin_bar(0);
		change_plugin_bar(1);
	}else if(e.data.action == "YEEKIT_RESET_LANGUAGE"){
		if(e.data.isContinueTrans == 1){//继续翻译：在当前翻译完成的基础之上接着翻译
			continue_translate(e.data.sourceLang,e.data.targetLang);
		}
			PLUGIN_SOURCE_LANGUAGE = e.data.sourceLang;
			PLUGIN_TARGET_LANGUAGE = e.data.targetLang;
		
		
	}else if(e.data.action == "ABOUT"){
		window.alert("译库网页翻译：一键秒翻，轻松浏览外文网站\n版本号:1.6.0 \n最新动态：\n1） 全面提升翻译速度，让您尽享”秒翻”的精彩\n2） 优化了语言的智能识别、自动弹出功能\n3） 增强了各浏览器版本划词翻译的功能");
	}else if(e.data.action == "RGTRANS_COUNT"){
		rgTransCnt();
	}else if(e.data.action == "CHANGE_YEETOOL_HEIGHT"){
		document.getElementById("yeetool").style.height = '150px';
	}else if(e.data.action == "CHANGE_YEETOOL_RESTORE"){
		document.getElementById("yeetool").style.height = '50px';
	}else if(e.data.action == "CONFIG"){
		//发请求到background,打开插件配置页面
		chrome.runtime.sendMessage({CONFIG:1},function(response){});
	}else if(e.data.action == "LOGO"){
		//发请求到background,打开LOGO页面
		chrome.runtime.sendMessage({LOGO:1},function(response){});
	}else if(e.data.action == "FAQ"){
		//发请求到background,打开FAQ页面
		chrome.runtime.sendMessage({FAQ:1},function(response){});
	}else if(e.data.action == "PERSON_TRANS"){
		//发请求到background,打开人工翻译页面
		chrome.runtime.sendMessage({PERSON_TRANS:1},function(response){});
	}
}

/**
 * 存储原文DOM对象
 */
function save_source_element(){
	var children = $("body").children().not($("#yeetool"));

	//给body下面的每个子DOM对象添加id
	$.each(children,function(index,ele){
		//添加id
		if(!($("body").children().not($("#yeetool")).eq(index).attr("id"))){
			$("body").children().not($("#yeetool")).eq(index).attr("id","yeeId_"+index);
		}
		//存储原文DOM对象
		sourceNewObj[$("body").children().not($("#yeetool")).eq(index).attr("id")] = $("body").children().not($("#yeetool")).eq(index).clone();
	});
	
}

/**
 * 存储译文DOM对象
 */
function save_target_element(){
	var children = $("body").children().not($("#yeetool"));

	//给body下面的每个子DOM对象添加id
	$.each(children,function(index,ele){
		//存储译文DOM对象
		targetNewObj[$("body").children().not($("#yeetool")).eq(index).attr("id")] = $("body").children().not($("#yeetool")).eq(index).clone();
	});
	
}

/**
 * 查看原文
 */
function Suffer_Source(flag){


if(total_number_of_content>0){
		
		//通过缓存对象还原原文网页
		var domsize = $("body").children().not($("#yeetool")).length;
		for(var i = 0;i < domsize+1;i++){
			$("body").children().not($("#yeetool")).eq(i).replaceWith($(sourceNewObj[$("body").children().not($("#yeetool")).eq(i).attr("id")]).clone());
		}
		
		
		//转换按钮状态为“查看译文”
		var frm = document.getElementById("yeetool");
		frm.contentWindow.postMessage({
			action : "YEEKIT_LOAD_TARGET_BUTTON",
			flag:flag//flag 0的常规翻译显示译文 1继续翻译显示译文
		}, "*");		

	}		

}

/**
 * 查看译文
 */
function Suffer_Target(){
	// save_source_element();

	//通过缓存对象还原译文网页
	var domsize = $("body").children().not($("#yeetool")).length;
	for(var i = 0;i < domsize+1;i++){
		$("body").children().not($("#yeetool")).eq(i).replaceWith($(targetNewObj[$("body").children().not($("#yeetool")).eq(i).attr("id")]).clone());
	}


	//转换按钮状态为“查看原文”
	var frm = document.getElementById("yeetool");
	frm.contentWindow.postMessage({
		action : "YEEKIT_LOAD_SOURCE_BUTTON"
	}, "*");
}



/**
 * 在当前已翻译的基础上接着翻译
 * source:源语言 target:需要翻译成的目标语言
 */
function continue_translate(source,target){

	//程序业务工作流程：

	//1.恢复功能条样式
	yeetool = document.getElementById("yeetool");
	yeetool.contentWindow.postMessage({
		action : "CONTINUE_TRANS"
	}, "*");
	//2.先转换为显示原文
	Suffer_Source(1);
}



//发送插件功能条创建初始化信息到功能条页面脚本
function send_msg_init(isAuto){
	yeetool.onload = function(){
		yeetool.contentWindow.postMessage({
			action : "YEEKIT_SHOW_PLUGIN",
			//是否为自动识别弹出
			is_auto:isAuto
		}, "*");
		yeetool.contentWindow.postMessage({
			action : "YEEKIT_SET_LANGUAGE",
			sourceLang : PLUGIN_SOURCE_LANGUAGE,
			targetLang : PLUGIN_TARGET_LANGUAGE,
			//语种列表初始化
			languageTypeList : ($.isEmptyObject(LANGUAGE_TYPE_LIST))?LANGUAGE_TYPE_LIST_DEFINED:LANGUAGE_TYPE_LIST

		}, "*");
		//点击时，源语言和目标语言一致也显示划词
		//if(PLUGIN_SOURCE_LANGUAGE!=PLUGIN_TARGET_LANGUAGE && PLUGIN_TARGET_LANGUAGE != "und")
		yeetool.contentWindow.postMessage({
			select_translation_flag : PLUGIN_SELECT_TRANSLATION

		}, "*");
	};
}

/**
 * 翻译字符长度计算
 */
function get_total_number_of_translation(){
	total_number_of_content = 0;
	walkTheDOM(document.body, function(node) {
	if (node.nodeType=== 3) { // Is it a Text node?
		var text = node.data.trim();
		var parent = node.parentNode;
		if (parent.nodeName != "SCRIPT" && parent.nodeName != "NOSCRIPT" && parent.nodeName != "STYLE" && parent.nodeName != 'TEXTAREA' && parent.nodeName != 'PRE' && parent.nodeName != 'CODE' && parent.id != 'yeebox') {
				if (text.length > 0 && text.length < 5120) {
					total_number_of_content += 1;
				}
			}
		}
	});
	// console.info(total_number_of_content);
	return total_number_of_content;
}

/**
 * DOM遍历
 */
function walkTheDOM(node, func) {
	func(node);
	node = node.firstChild;
	while (node) {
		walkTheDOM(node, func);
		node = node.nextSibling;
	}
}

/**
 * uuid序列号生成
 */
function create_uuid() {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	return uuid;
}

/**
 * 网页翻译 - 开始翻译
 */
function transBtnClick(sourcelang, targetlang) {

	//源语言,目标语言参数
	sourcelang_ = sourcelang;
	targetlang_ = targetlang;

	//翻译长度	
	//total_number_of_content
	
	percentage = 0;
	request_iter = 0;
	list_iter = 0;
	list_total = 0;
	translation_list = [];
	translation_node = [];
	if (sourcelang == targetlang && sourcelang != "und") {//如果目标语言和源语言相同,直接翻译结束,进度条干满
		progressBar(1.0);
	} else {
		var translateId = create_uuid();
		walkTheDOM(document.body, function(node) {

			if (node.nodeType === 3) { // Is it a Text node?

				var text = node.data.trim();
				var parent = node.parentNode;
				if (parent.nodeName != "SCRIPT"
						&& parent.nodeName != "NOSCRIPT"
						&& parent.nodeName != "STYLE"
						&& parent.nodeName != 'TEXTAREA'
						&& parent.nodeName != 'PRE'
						&& parent.nodeName != 'CODE'
						&& parent.id !='yeebox') {
					if (text.length > 0 && text.length < 5120) {
						try {
							JSON.parse(text);
							request_iter += 1;
							list_total += 1;
						} catch (err) {
							try {

								term_translation = dict[text];
								if (term_translation) {
									node.data = term_translation;
									sourceMap[term_translation]=text;//存储  “key:译文-->value:原文” 键值对
									transMap[text]=term_translation;//存储 “key:原文-->value:译文” 键值对
									request_iter += 1;
								} else {

									translation_list[list_iter] = text;
									translation_node[list_iter] = node;
									list_iter += 1;
									list_total += 1;
									if (list_iter == 20 || list_total == total_number_of_content){
										//翻译
										// console.log(translateId);
										list_translation(sourcelang_,targetlang_,translation_list,translation_node,translateId);
										list_iter = 0;
										translation_list = [];
										translation_node = [];
									}
									//translate(sourcelang_,targetlang_,text,node);
								}
							} catch (err) {
								request_iter += 1;
							}
						}
					}
				}
			}
		});

		Additional_Translate(sourcelang_,targetlang_);
		// console.info('total translation request time in the DOM: ' + request_iter);
	}
}

/**
 * 网页翻译 - 进度更新 - 通知到弹出框功能条
 */
function progressBar(index) {
	var frm = document.getElementById("yeetool");
	frm.contentWindow.postMessage({
		action : "YEEKIT_CHANGE_PROGRESSBAR",
		index : (index*100).toFixed(0)
	}, "*");
}

/**
 * 进度条加载 - 加载百分比计算
 */
function changeProgress(){
	progress = request_iter / total_number_of_content;
	currentpercentage = progress * 100;
	//console.log('current step:' + request_iter + '\t amount:' + total_number_of_content + '\t progress:' + progress);
	if (currentpercentage - percentage >= 1) {
		progressBar(percentage / 100);
		percentage = currentpercentage - currentpercentage % 1;
	}

	if(progress >= 0.95){
		progress = 1.0;
		progressBar(progress);
		//查看原文前保存译文
		save_target_element();
		// 发送“查看原文”消息
		var frm = document.getElementById("yeetool");
		frm.contentWindow.postMessage({
			action : "YEEKIT_LOAD_SOURCE_BUTTON"
		}, "*");
	}
}

/**
 * 网页翻译 - 渲染翻译元素
 */
function Additional_Translate(srcl,tgtl){
	
	var whatToObserve = {childList: true, attributes: true, subtree: true, attributeOldValue: true, attributeFilter: ['class', 'style']};
	var mutationObserver = new MutationObserver(function(mutationRecords) {
		for(var p = 0; p < mutationRecords.length; p++){
			var mutationRecord = mutationRecords[p];
			if (mutationRecord.type === 'childList') {
				if (mutationRecord.addedNodes.length > 0) {
					additional_request_iter = 0;
					for(var i = 0 ; i < mutationRecord.addedNodes.length; i++){
						walkTheDOM(mutationRecord.addedNodes[i], function(node) {
							if (node.nodeType === 3) { 
								var text = node.data.trim();
								var parentnode = node.parentNode;
								try {
									JSON.parse(text);
								} catch (err) {
									if (text.length > 0 && text.length < 5120) {
										if (parentnode.nodeName != "SCRIPT"
												&& parentnode.nodeName != "NOSCRIPT"
												&& parentnode.nodeName != "STYLE"
												&& parentnode.nodeName != 'TEXTAREA'
												&& parentnode.nodeName != 'PRE'
												&& parentnode.nodeName != 'CODE'
												&& parentnode.id!='yeebox') {
											try {
												term_translation = dict[text];
												if (term_translation) {
													node.data = term_translation;
													sourceMap[term_translation]=text;//存储  “key:译文-->value:原文” 键值对
													transMap[text]=term_translation;//存储 “key:原文-->value:译文” 键值对
													request_iter += 1;
												} else {
													translation_list[list_iter] = text;
													translation_node[list_iter] = node;
													list_iter += 1;
													list_total += 1;
													if (list_iter == 20 || list_total == total_number_of_content){
														list_translation(sourcelang_,targetlang_,translation_list,translation_node);
														list_iter = 0;
														translation_list = [];
														translation_node = [];
													}
												}
											} catch (err) {
												console.log("dom change translate error:"+err.message);
											}
										}
									}
								}
							}
						});
					}
				}
			}
		}
	});
	mutationObserver.observe(document.body, whatToObserve);
}

/**
 * 异步批量翻译
 */
function list_translation(src,tgt,texts,nodes,translateId){

	if(translateId != undefined){
		//为解决复杂网页跨域失败问题,将请求权交给background
		chrome.runtime.sendMessage({action:"list_translate_action",src:src,tgt:tgt,texts:texts,translateId:translateId,website:window.location.hostname,weburl:window.location.href},function(response){
			// console.log(response);
			var translation_result = response.data.data;
			if(nodes[0].data != translation_result[0]){
				for(var i = 0 ; i < translation_result.length ; i++){
					var translation = translation_result[i];
					text = texts[i];
					if(tgt=="zh"){
						translation = translation_result[i].replace(/\s+/g, "");
					}

					sourceMap[encodeURI(text)] = encodeURI(translation);
					targetMap[encodeURI(translation)] = encodeURI(text);


					if(undefined !== nodes[i].data){
						nodes[i].data = translation;
					}else{
						nodes[i] = translation;
					}
					
					request_iter += 1;
					changeProgress();
				}
			}else{
				for(var i = 0 ; i < translation_result.length ; i++){					
					request_iter += 1;
					changeProgress();
				}
			}
		});
	}
	


}




//渲染划词翻译显示框
function addYeebox(ev){
	var selectText = getSelectionText();
	if(selectText.replace(/(^\s*)|(\s*$)/g, "").length>0){
		//源语言与目标语言不一致时才弹出翻译框(前面已经用标志限制了按钮，所以此处不用再限制)
			var yeebox = document.getElementById('yeebox');
			if(yeebox!=null){
				yeebox.parentNode.removeChild(yeebox);
			}
			var divElement = document.createElement('div');
			divElement.charset = 'utf-8';
			
			var ev = ev||window.event;
			var x=0;
			var y=0;
			if(ev.pageX || ev.pageY){
				x = ev.pageX;
				y = ev.pageY;
			} else{
				x = ev.clientX + document.body.scrollLeft - document.body.clientLeft;
				y = ev.clientY + document.body.scrollTop - document.body.clientTop;
			}

			//弹出框坐标自动调整策略
			/*var autoX = 380;
			var autoY = 250;
			if(document.body.clientHeight - y < autoY){//网页可见区域高度 - 当前鼠标所在高度  < 划词框的高度     ,则加y值一个划词框的高度
				y = y - autoY;
			}
			if(document.body.clientWidth - x < autoX){//网页可见区域宽度 - 当前鼠标所在宽度  < 划词框的宽度     ,则加x值一个划词框的宽度
				x = x - autoX;
			}*/
			
			//弹出框坐标自动调整策略
			var autoX = 380;
			var autoY = 250;
			var heigao = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
			var widkuan = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
			if(heigao - y < autoY){//网页可见区域高度 - 当前鼠标所在高度  < 划词框的高度     ,则加y值一个划词框的高度
				y = y - autoY;
			}
			if(widkuan - x < autoX){//网页可见区域宽度 - 当前鼠标所在宽度  < 划词框的宽度     ,则加x值一个划词框的宽度
				x = x - autoX;
			}
			
			left=ev.clientX,top=ev.clientY;
			document.body.appendChild(divElement);
			divElement.id = 'yeebox';
			divElement.name = 'yeebox';
			divElement.style.position = "absolute";
			divElement.style.left = x + 'px';
			divElement.style.top = y + 'px';
			divElement.style.height = '210px';
			divElement.style.width = '350px';
			divElement.style.zIndex = 2147483647;
			divElement.style.border = 'solid 1px #0093D5';
			divElement.style.background='#FFFFFF';
			divElement.style.fontSize='12px';
			divElement.style.borderRadius='5px';
			divElement.style.boxShadow='0px 0px 5px #0093D5';
			
			var boxhtml = '<div style="text-align: left;margin-top:5px;padding-left:5px;">选择语言：<select id="targetLanguage" style="height:20px;padding:0px 0px;">';			
			//循环语种列表对象,得到语种对象
			if($.isEmptyObject(LANGUAGE_TYPE_LIST)){
				LANGUAGE_TYPE_LIST = LANGUAGE_TYPE_LIST_DEFINED;	
			}
			$.each(LANGUAGE_TYPE_LIST,function(langCode,langName){
				boxhtml += '<option value="'+langCode+'" >'+langName+'</option>';
			});
			
			boxhtml += '</select></div><div id="transRes" style="text-align: left;margin:0 auto;margin-top:10px;padding-left:5px;padding-top:5px;font-size:14px;width:93%;height:147px;overflow:auto;border:1px solid lightgrey;border-radius:5px;cursor:text;"><div style="color:gray;margin-top:60px;text-align:center;font-size:12px;">翻译中 . . . </div></div>'+
			'<div style="text-align: left;color:#999999;margin-top:0px;margin-left:10px;font-size:12px;width:340;position:relative;font-family:微软雅黑;">翻译内容由译库提供'+
			'<a href="http://www.yeekit.com" target="blank_" text-align="right" style="color:#000099;position:absolute;right:10px;">发现更多精彩</a></div>';
			
			divElement.innerHTML= boxhtml;
			
			divElement.onmousemove = function(){
				document.onclick="";
				document.onmouseup="";
			};
			divElement.onmouseout = function(){
				document.onmouseup = addYeebox;
			};
			
			document.getElementById("targetLanguage").value = PLUGIN_TARGET_LANGUAGE;
			document.getElementById("targetLanguage").style.disabled = "disabled";//禁用
			
			transSelectText(PLUGIN_SOURCE_LANGUAGE,PLUGIN_TARGET_LANGUAGE,selectText);
			
			//监听选择其他语言
			document.getElementById("targetLanguage").addEventListener("change", function(){
					changeLanguage(PLUGIN_SOURCE_LANGUAGE,selectText);
			}, false);
		//}
	}else{
		//监听到鼠标在yeebox里时，不关闭box
		var is_close = true;
		var yeebox = document.getElementById('yeebox');
		if(yeebox!=null){
			yeebox.addEventListener("mousemove", function(){
				is_close = false;
			}, false);
		}
		//不在yeebox里，点击其他地方时，关闭box
		if(is_close){
			removeYeebox();
		}
	}
}

//移除划词翻译框
function removeYeebox(){
	var createYeeboxJs2 = $('#createYeeboxJs');
	if (createYeeboxJs2 != null) {
		$('#createYeeboxJs').remove();
	}

	var yeebox = $('#yeebox');
	if (yeebox != null) {
		$('#yeebox').remove();
	}
}

//划词翻译工具方法 - 获取选中文本
function getSelectionText() {
	if (window.getSelection) {
		return window.getSelection().toString();
	} else if (document.selection && document.selection.createRange) { //if is IE
		return copytext_keleyi_com = document.selection.createRange().text;
	}
	return '';
}

//翻译选中划词文本
function transSelectText(sour,tar,text){

	//语种识别
	//为解决复杂网页跨域失败问题,将请求权交给background
	chrome.runtime.sendMessage({action:"lang_type_action",lang_text:text,website:window.location.hostname,weburl:window.location.href},
		function(response){
			//console.log(response);
			sour =  response.lang_type;
			go_translate(sour,tar,text);
		}
	);


}

//调用background接口进行翻译(监听在translate.js)
function go_translate(sour,tar,text){
	if(tar == "" || tar == null){
		tar = document.getElementById("targetLanguage").value;
	}
	
	tar = tar.toLowerCase();
	sour = sour.toLowerCase();
	if(sour == "zh-cn"){
		sour = "zh";
	}
	if(tar == "zh-cn"){		
		tar = "zh";
	}
	var translateId = create_uuid();
	//为解决复杂网页跨域失败问题,将请求权交给background
	chrome.runtime.sendMessage({action:"translate_action",sour:sour,tar:tar,text:text,translateId:translateId,website:window.location.hostname,weburl:window.location.href},
		function(response){
		var text = response.text;
		//如果语言为中文,去空格
		if(tar == "zh"){
			text = (text+"").replace(/\s+/g, "");
		}
			if(sour==tar){
				document.getElementById('transRes').innerHTML = text;
			}else{
				var json = "";
				try{
					json = text;
			    }catch(e){
					document.getElementById('yeebox').innerHTML='<div style="font-size:14px; text-align:center; padding-top:25%; font-family: \'microsoft yahei\';">远程接口调用失败，翻译失败!</div>';
				}
				var resTranslation = text;

				if(document.getElementById('transRes')!="undefined"){
					if(resTranslation){
						document.getElementById('transRes').innerHTML = resTranslation;
					}else{
						document.getElementById('transRes').innerHTML = '<div style="font-size:12px; text-align:center; padding-top:60px; font-family: \'microsoft yahei\'; color:#800080;">暂不支持对该语言的翻译!</div>';
					}
				}
			}

		}
	);

}



//选择其他语言
function changeLanguage(sour,text){
	var newTarget = document.getElementById("targetLanguage").value;
//	if(sour==newTarget){
//		document.getElementById('transRes').innerHTML = text;
//	}else{
		transSelectText(sour,newTarget,text);
//	}
}